All graphics operations are performed in graphics ports. Before a color graphics port can be used, it must be allocated with the OpenCPort procedure and initialized with the InitCPort procedure. Normally, your application does not call these procedures directly. Instead, your application creates a color graphics port by using the GetNewCWindow or NewCWindow function (described in the chapter "Window Manager" in Inside Macintosh: Macintosh Toolbox Essentials ) or the NewGWorld function (described in the chapter "Offscreen Graphics Worlds" in this book). These functions automatically call OpenCPort , which in turn calls InitCPort .
Listing 4-1 shows a simplified application-defined procedure called DoNew that uses the Window Manager function GetNewCWindow to create a color graphics port.
Listing 1 Using the Window Manager to create a color graphics port
PROCEDURE DoNew (VAR window: WindowPtr);
VAR
windStorage: Ptr; {memory for window record}
BEGIN
window := NIL;
{allocate memory for window record from previously allocated block}
windStorage := MyPtrAllocationProc;
IF windStorage <> NIL THEN {memory allocation succeeded}
BEGIN
IF gColorQDAvailable THEN {use Gestalt to determine color availability}
window := GetNewCWindow(rDocWindow, windStorage, WindowPtr(-1))
ELSE {create a basic graphics port for a black-and-white screen}
window := GetNewWindow(rDocWindow, windStorage, WindowPtr(-1));
END;
IF (window <> NIL) THEN
SetPort(window);
END;
You can use GetNewCWindow to create color graphics ports whether or not a color monitor is currently installed. So that most of your window-handling code can handle color windows and black-and-white windows identically, GetNewCWindow returns a pointer of type WindowPtr (not of type CWindowPtr ).
A window pointer points to a window record ( WindowRecord ), which contains a GrafPort record. If you need to check the fields of the color graphics port associated with a window, you can coerce the pointer to the GrafPort record into a pointer to a CGrafPort record.
You can allow GetNewCWindow to allocate the memory for your window record and its associated basic graphics port. You can maintain more control over memory use, however, by allocating the memory yourself from a block allocated for such purposes during your own initialization routine, and then passing the pointer to GetNewWindow , as shown in Listing 4-1 .
To dispose of a color graphics port when you are finished using a color window, you normally use the DisposeWindow procedure (if you let the Window Manager allocate memory for the window) or the CloseWindow procedure (if you allocated memory for the window). If you use the CloseWindow procedure, you also dispose of the window record containing the graphics port by calling the Memory Manager procedure DisposePtr . You use the DisposeGWorld procedure when you are finished with a color graphics port for an offscreen graphics world.